/**
 * Copyright (c) 2005 - 2007 FeyaSoft Corp. All Rights Reserved.
 */
package com.feyaSoft.home.dao.feedback;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.feyaSoft.home.dao.base.BaseHibernateDao;
import com.feyaSoft.home.dao.base.BaseSearchResult;
import com.feyaSoft.home.dao.base.DataAccessException;
import com.feyaSoft.home.dao.base.ObjectNotFoundException;
import com.feyaSoft.home.hibernate.feedback.Feedback;

/**
 * @author Fenqiang Zhuang
 * @Oct 10, 2007
 * 
 * This file is used to .....
 */
public class FeedbackDaoImpl extends BaseHibernateDao implements FeedbackDao {

	private final static Log log = LogFactory.getLog(FeedbackDaoImpl.class);
	private SessionFactory sessionFactory;

	public BaseSearchResult search(FeedbackSearchCriteria sc) throws Exception {
		Session session = sessionFactory.getCurrentSession();

		Criteria basicCriteria = session.createCriteria(Feedback.class)
				.addOrder(Order.desc("updateDate"));

		// dealing with parent id
		if (sc.getParentId() != null ) {
			basicCriteria.add(Restrictions.eq("parentId", sc.getParentId()));
		}

		// for status: active?
		if (sc.getStatus() != null && sc.getStatus().length()>0) {
			basicCriteria.add(Restrictions.eq("status", sc.getStatus()));
		} 

		// for feedbacks
		if (sc.getSubjects() != null) {
			String[] alias = { "subject", "description" };
			Disjunction disjunction = buildDisjunction(sc.getSubjects(),
					SQL_LIKE, alias);
			basicCriteria.add(disjunction);
		}

		return commonSearch(session, basicCriteria, sc);
	}

	/**
	 * load feedback now...
	 * 
	 * @param id
	 * @return
	 * @throws ObjectNotFoundException
	 * @throws DataAccessException
	 */
	public Feedback loadFeedbackById(Long id) throws ObjectNotFoundException,
			DataAccessException {
		Feedback feedback = null;
		try {
			Session session = sessionFactory.getCurrentSession();
			feedback = (Feedback) session.get(Feedback.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			log.fatal("loadFeedbackById failed" + e.getMessage());
		}
		return feedback;
	}

	/**
	 * save or update feedback
	 */
	public Long saveOrUpdate(Feedback feedback) throws Exception {
		Long id = null;
		try {
			Session session = sessionFactory.getCurrentSession();
			session.saveOrUpdate(feedback);
			id = feedback.getId();
		} catch (Exception e) {
			e.printStackTrace();
			log.fatal("saveOrUpdate feedback failed, " + e.getMessage());
		}

		return id;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
